﻿namespace ChinaUnicom.TrafficControl
{
    using ChinaUnicom.Net;
    using ChinaUnicom.Storage;
    using Newtonsoft.Json;
    using System.Threading;

    public sealed class Traffic
    {
        static object locker = new object();

        static Traffic current;
        public static Traffic Current
        {
            get
            {
                if (current == null)
                {
                    lock (locker)
                    {
                        if (current == null)
                        {
                            current = JsonStorage.Restore<Traffic>();
                            current = (current == null ? new Traffic() : current);
                        }
                    }
                }

                return current;
            }
        }

        public Traffic()
        {
            OthersDataLength = 0;
            CellularDataLength = 0;
        }

        public void TryCheck(long length)
        {
            try
            {
                Monitor.Enter(locker);

                if (NetHelper.Network.Type == NetworkType.Cellular)
                {
                    CellularDataLength += length;
                }
                else
                {
                    OthersDataLength += length;
                }
            }
            finally
            {
                Monitor.Exit(locker);
            }
        }

        public long OthersDataLength { get; set; }

        public long CellularDataLength { get; set; }

        [JsonIgnore]
        public long Length { get { return OthersDataLength + CellularDataLength; } }

        public void Store()
        {
            JsonStorage.Store(this);
        }
    }
}
